import { AuthProvider, HttpError, UserIdentity } from 'react-admin';
import { AvatarGenerator } from 'random-avatar-generator';
import decodeJwt from 'jwt-decode';
import { API_URL } from './constants/endpoints';
import { stringify } from 'query-string';



const authProvider: AuthProvider = {

    login: ({ username, password }) => {
        const request = new Request(`${API_URL}/login`, {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });
        return new Promise(
            (resolve, reject) => {
                fetch(request)
                    .then(response =>
                        response.text().then(text => ({
                            status: response.status,
                            statusText: response.statusText,
                            headers: response.headers,
                            body: text,
                        }))
                    )
                    .then(({ status, statusText, headers, body }) => {
                        let json;
                        try {
                            json = JSON.parse(body);
                        } catch (e) {
                            // 没有json， 没事
                        }

                        if (status === 401) {
                            return reject(
                                new HttpError(
                                    "LOGIN_UNATUH",
                                    status,
                                    json
                                )
                            );
                        }

                        if (status < 200 || status >= 300) {
                            return reject(
                                new HttpError(
                                    (json && json.message) || statusText,
                                    status,
                                    json
                                )
                            );
                        }
                        localStorage.setItem('token', json.token)
                        return resolve({
                            data: { ...json },
                        })
                    }).catch(error => {
                        reject(error)

                    })
            }
        )

    },
    logout: () => {
        localStorage.removeItem('token');
        return Promise.resolve();
    },
    checkError: error => Promise.resolve(),

    checkAuth: () => {
        const token = localStorage.getItem('token');
        if (!token) {
            return Promise.reject();
        }
        try {
            const decodedToken: any = decodeJwt(token);
            console.log(decodedToken);
            
            const nowNumber = new Date().getTime();
            if (parseInt(decodedToken.exp) * 1000 < nowNumber) {
                //处理过期
                localStorage.removeItem('token');
                return Promise.reject("TOKEN_EXPIRED");
            }
            return Promise.resolve();
        } catch (error) {
            // localStorage.removeItem('token');
            return Promise.reject(error);
        }
      
    },

    getPermissions: async () => {
       
        const token = localStorage.getItem('token');
        if(!token){
            return Promise.reject("请先登录");
        }
        const decodedToken: any = decodeJwt(token);
        const query = {
            sort: JSON.stringify(["createdAt", "DESC"]),
            range: JSON.stringify([0,1000]),
            filter: JSON.stringify({
                userId: decodedToken.userId,
            }),
        };
        const request = new Request(`${API_URL}/permissions?${stringify(query)}`, {
            method: 'GET',
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });

        if (token) {
            request.headers.set('Authorization', `Bearer ${token}`);
        }
        const response = await fetch(request);
        return response.json();
    },
    
    getIdentity: async ():Promise<UserIdentity> => {
        const token = localStorage.getItem("token")
        if(!token){
            return Promise.reject("请先登录");
        }
        const decodedToken: any = decodeJwt(token);
        const request = new Request(`${API_URL}/users/${decodedToken.userId}`, {
            method: 'GET',
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });
        if (token) {
            request.headers.set('Authorization', `Bearer ${token}`);
        }
        return new Promise(async (res, rej) => {
            try {
                const response = await fetch(request);
                const profile = await response.json();
                const generator = new AvatarGenerator();
                res({
                    id: profile.id,
                    fullName: profile.username,
                    avatar: generator.generateRandomAvatar(),
                    roles: profile.roles,
                    firms: profile.firms,
                });
            } catch (err) {
                console.error(err);
                rej(err);
            }
        })
        

        

    }

};

export default authProvider;
